//
//  UIKit.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/4/4.
//

import Foundation
import SwiftUI

/// 一个 SwiftUI View，注入一个 UIKit UIViewController 提供器
struct UIKitViewControllerAccessor: UIViewControllerRepresentable {
    var callback: (UIViewController) -> Void

    func makeUIViewController(context _: Context) -> UIViewController {
        let viewController = UIViewController()
        DispatchQueue.main.async {
            if let parent = viewController.parent {
                callback(parent)
            }
        }
        return viewController
    }

    func updateUIViewController(_: UIViewController, context _: Context) {}
}

extension UIApplication {
    static func topViewController(base: UIViewController? = UIApplication.shared.connectedScenes
        .compactMap { ($0 as? UIWindowScene)?.keyWindow }
        .first?.rootViewController) -> UIViewController?
    {
        if let nav = base as? UINavigationController {
            return topViewController(base: nav.visibleViewController)
        }

        if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
            return topViewController(base: selected)
        }

        if let presented = base?.presentedViewController {
            return topViewController(base: presented)
        }

        return base
    }
}
